﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DocumentManager
{
    public static class GlobalSettings
    {
        public static SettingsCollection Settings = new SettingsCollection();

    }
    
    public class SettingsCollection : Dictionary<string, object>
    {
        /// <summary>
        /// Gets or sets a value at a specified key.  For set operations: when the key does not exist, it's created
        /// </summary>
        /// <param name="key">The key name</param>
        /// <returns>The object stored at the specific key</returns>
        new public object this[string key]
        {
            get
            {
                return base[key];
            }
            set
            {
                if (this.ContainsKey(key))
                {
                    base[key] = value;
                }
                else
                {
                    this.Add(key, value);
                }
            }
        }

        /// <summary>
        /// Creates a new settings collection
        /// </summary>
        public SettingsCollection() : base(StringComparer.CurrentCultureIgnoreCase) { }

        /// <summary>
        /// Attempts to retrieve a value matching type T from the collection
        /// </summary>
        /// <typeparam name="T">The type of value we're expecting</typeparam>
        /// <param name="key">The value's key</param>
        /// <param name="value">The resulting value</param>
        /// <returns>true if the value exists and matches type T, false otherwise</returns>
        public bool TryGetTypedValue<T>(string key, out T value)
        {
            object val = null;

            if (this.TryGetValue(key, out val) && val is T)
            {
                value = (T)val;
                return true;
            }

            value = default(T);

            return false;
        }

        /// <summary>
        /// Gets a value of type T from the settings collection.  If no value matching type T exists, 
        /// returns the default.
        /// </summary>
        /// <typeparam name="T">The value type to search for</typeparam>
        /// <param name="key">Key location</param>
        /// <param name="defaultValue">A default value to return, if no value found</param>
        /// <returns>Either the typed value, or the defaultValue</returns>
        public T GetTypedValue<T>(string key, T defaultValue)
        {
            T val = defaultValue;
            if (this.TryGetTypedValue<T>(key, out val))
            {
                return val;
            }
            return defaultValue;
        }
    }
}
